package com.ssm.maven.core.admin;

import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.baidu.ueditor.ActionEnter;
import com.ssm.maven.core.entity.UeditorResult;
import com.ssm.maven.core.util.LoadPropertiesFileUtil;

/**
 * Created by lei on 2017/5/20.
 */

public class UEditorController
{

    public static String upload(HttpServletRequest request, String rootPath) throws IOException
    {
        String result = new ActionEnter(request, rootPath).exec();
        String actionType = request.getParameter("action");
        if (StringUtils.isNotBlank(result) && (actionType.equals("uploadimage") || actionType.equals("uploadvideo")))
        {
            try
            {
                UeditorResult ue = JSON.parseObject(result, UeditorResult.class);
                String url = ue.getUrl();
                String path = MessageFormat.format("{0}{1}", rootPath, url);
                String destDir = MessageFormat.format("{0}{1}", LoadPropertiesFileUtil.props.getProperty("uploadPath"),
                        url);
                File file = new File(path);
                FileUtils.copyFileToDirectory(file, new File(destDir));
                // FileUtils.deleteDirectory(file);
            }
            catch (Exception e)
            {
            }
        }

        return result;

    }

}
